package vn.njai.thousand_english_word.Activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Typeface;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.*;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import butterknife.ButterKnife;
import butterknife.InjectView;
import com.facebook.*;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;
import com.facebook.widget.*;
import com.gc.materialdesign.views.ButtonRectangle;
import com.gc.materialdesign.views.Slider;
import com.gc.materialdesign.widgets.Dialog;
import vn.njai.thousand_english_word.Entities.HistoryNodeItem;
import vn.njai.thousand_english_word.R;
import vn.njai.thousand_english_word.Utils.DataManager;
import vn.njai.thousand_english_word.Utils.Utils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * Created by VUONG on 12/14/2014.
 */
public class SettingActivity extends ActionBarActivity implements View.OnClickListener{
    private String TAG = "SettingActivity";
    private Context mContext;
    @InjectView(R.id.toolbar) public Toolbar mToolbar;
    @InjectView(R.id.btnGuild) public ButtonRectangle mGuildBtn;
    @InjectView(R.id.btnRatting) public ButtonRectangle mRattingBtn;
    @InjectView(R.id.btnReset) public ButtonRectangle mResetBtn;
    @InjectView(R.id.btnAbout) public ButtonRectangle mAboutBtn;
    @InjectView(R.id.sliderVolume) public Slider mVolumeSlider;

    public static void start(Context context) {
        Intent intent = new Intent(context,SettingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        mContext = this;
        init();
        uiHelper = new UiLifecycleHelper(this, callback);
        uiHelper.onCreate(savedInstanceState);

        if (savedInstanceState != null) {
            String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
            pendingAction = PendingAction.valueOf(name);
        }
        // Can we present the share dialog for regular links?
        canPresentShareDialog = FacebookDialog.canPresentShareDialog(this,
                FacebookDialog.ShareDialogFeature.SHARE_DIALOG);
        // Can we present the share dialog for photos?
        canPresentShareDialogWithPhotos = FacebookDialog.canPresentShareDialog(this,
                FacebookDialog.ShareDialogFeature.PHOTOS);
    }

    public void init(){
        ButterKnife.inject(this);
        initActionBar();
        //mFacebookShareBtn.setOnClickListener(this);
        mResetBtn.setOnClickListener(this);
        mAboutBtn.setOnClickListener(this);
        mRattingBtn.setOnClickListener(this);
        mGuildBtn.setOnClickListener(this);

        //mFacebookLoginBtn.setBackgroundColor(getResources().getColor(R.color.material_blue_700));
        mResetBtn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        mAboutBtn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        mRattingBtn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        mVolumeSlider.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
        mGuildBtn.setBackgroundColor(getResources().getColor(R.color.colorPrimary));

        mVolumeSlider.setValue(DataManager.getInstance().loadVolume());
        mVolumeSlider.setOnDragListener(new View.OnDragListener() {
            @Override
            public boolean onDrag(View view, DragEvent dragEvent) {
                return false;
            }
        });
        mVolumeSlider.setOnValueChangedListener(new Slider.OnValueChangedListener() {
            @Override
            public void onValueChanged(int value) {
                DataManager.getInstance().saveVolume(value);
            }
        });

//        mFacebookLoginBtn.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
//            @Override
//            public void onUserInfoFetched(GraphUser user) {
//                SettingActivity.this.user = user;
//                updateUI();
//                // It's possible that we were waiting for this.user to be populated in order to post a
//                // status update.
//                handlePendingAction();
//            }
//        });

    }

    private void initActionBar(){
        mToolbar.setTitle(getString(R.string.actionbar_title_setting));
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_menu_back);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle presses on the action bar items
        switch (item.getItemId()) {
            case android.R.id.home:
                finish();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.btnGuild:
                GuildActivity.start(mContext,false);
                break;
            case R.id.btnRatting:
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setData(Uri.parse("market://details?id="+ Utils.mAppRatingLink));
                Log.e(TAG,"btnRatting: "+"market://details?id="+ Utils.mAppRatingLink);
                startActivity(intent);
                break;
            case R.id.btnReset:
                final Dialog dialog = new Dialog(mContext,mContext.getString(R.string.dialog_reset_title), mContext.getString(R.string.dialog_reset_question));
                dialog.show();
                Typeface face=Typeface.createFromAsset(mContext.getAssets(),mContext.getString(R.string.font_name));
                dialog.getButtonAccept().getTextView().setTypeface(face);
                dialog.getButtonCancel().getTextView().setTypeface(face);
                dialog.getButtonAccept().setText(mContext.getString(R.string.dialog_reset_ok));
                dialog.getButtonCancel().setText(mContext.getString(R.string.dialog_reset_cancel));
                dialog.getButtonAccept().setRippleSpeed(10);
                dialog.getButtonCancel().setRippleSpeed(10);
                dialog.setOnAcceptButtonClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        SharedPreferences.Editor prefsEditor = DataManager.getInstance().mPrefs.edit();
                        prefsEditor.putString("IsLoadFile", "false");
                        prefsEditor.commit();
                        DataManager.getInstance().mLearning = null;
                        DataManager.getInstance().mHistoryData = null;
                        DataManager.getInstance().mNeedLearn = null;
                        DataManager.getInstance().saveLearningList();
                        DataManager.getInstance().saveHistoryList();
                        DataManager.getInstance().saveNeedLearnList();
                        dialog.dismiss();
                        MainActivity.me.finish();
                        finish();
                        LoadingActivity.start(mContext);
                    }
                });

                break;
            case R.id.btnAbout:
                AboutActivity.start(mContext);
                break;
        }
    }

    public class Adapter extends ArrayAdapter<HistoryNodeItem> {

        public class ViewHolder{
            @InjectView(R.id.txtWord) public TextView word;
            @InjectView(R.id.viewShow) public View showView;
            @InjectView(R.id.viewAll) public View allView;
            @InjectView(R.id.txtRank) public TextView rank;
            @InjectView(R.id.txtPhonetic) public TextView phonetic;
            @InjectView(R.id.txtMeans) public TextView mean;
            public ViewHolder(View view){
                ButterKnife.inject(this,view);
            }
        }

        public Adapter() {
            super(mContext, 0, new ArrayList<HistoryNodeItem>());
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // Get the data item for this position
            View view = convertView;
            final ViewHolder viewHolder;
            final HistoryNodeItem item = getItem(position);
            // Check if an existing view is being reused, otherwise inflate the view
            if (view == null) {
                view = LayoutInflater.from(getContext()).inflate(R.layout.custom_node_history, parent, false);
                viewHolder = new ViewHolder(view);
                view.setTag(viewHolder);
            }else{
                viewHolder = (ViewHolder) view.getTag();
            }
            viewHolder.word.setText(item.mWord);
            viewHolder.rank.setText(item.mRank + "");
            viewHolder.phonetic.setText(item.mPhonetic);
            viewHolder.mean.setText(item.mMeans);
            if(item.mIsShow == true){
                viewHolder.showView.setVisibility(View.VISIBLE);
            }else{
                viewHolder.showView.setVisibility(View.GONE);
            }
            viewHolder.allView.setBackgroundColor(item.mColor);
            return view;
        }
    }
    private static final String PERMISSION = "publish_actions";
    private static final Location SEATTLE_LOCATION = new Location("") {
        {
            setLatitude(47.6097);
            setLongitude(-122.3331);
        }
    };

    private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";
    private TextView greeting;
    private PendingAction pendingAction = PendingAction.NONE;
    private ViewGroup controlsContainer;
    private GraphUser user;
    private GraphPlace place;
    private List<GraphUser> tags;
    private boolean canPresentShareDialog;
    private boolean canPresentShareDialogWithPhotos;

    private enum PendingAction {
        NONE,
        POST_PHOTO,
        POST_STATUS_UPDATE
    }
    private UiLifecycleHelper uiHelper;

    private Session.StatusCallback callback = new Session.StatusCallback() {
        @Override
        public void call(Session session, SessionState state, Exception exception) {
            onSessionStateChange(session, state, exception);
        }
    };

    private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
        @Override
        public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
            Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
        }

        @Override
        public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
            Log.d("HelloFacebook", "Success!");
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        uiHelper.onResume();

        // Call the 'activateApp' method to log an app event for use in analytics and advertising reporting.  Do so in
        // the onResume methods of the primary Activities that an app may be launched into.
        AppEventsLogger.activateApp(this);

        updateUI();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        uiHelper.onSaveInstanceState(outState);

        outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
    }

    @Override
    public void onPause() {
        super.onPause();
        uiHelper.onPause();

        // Call the 'deactivateApp' method to log an app event for use in analytics and advertising
        // reporting.  Do so in the onPause methods of the primary Activities that an app may be launched into.
        AppEventsLogger.deactivateApp(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        uiHelper.onDestroy();
    }

    private void onSessionStateChange(Session session, SessionState state, Exception exception) {
        if (pendingAction != PendingAction.NONE &&
                (exception instanceof FacebookOperationCanceledException ||
                        exception instanceof FacebookAuthorizationException)) {
            new AlertDialog.Builder(SettingActivity.this)
                    .setTitle(R.string.cancelled)
                    .setMessage(R.string.permission_not_granted)
                    .setPositiveButton(R.string.ok, null)
                    .show();
            pendingAction = PendingAction.NONE;
        } else if (state == SessionState.OPENED_TOKEN_UPDATED) {
            handlePendingAction();
        }
        updateUI();
    }

    private void updateUI() {
        Session session = Session.getActiveSession();
        boolean enableButtons = (session != null && session.isOpened());

        //mFacebookShareBtn.setEnabled(enableButtons || canPresentShareDialog);
//        postPhotoButton.setEnabled(enableButtons || canPresentShareDialogWithPhotos);
//        pickFriendsButton.setEnabled(enableButtons);
//        pickPlaceButton.setEnabled(enableButtons);

//        if (enableButtons && user != null) {
//            profilePictureView.setProfileId(user.getId());
//            greeting.setText(getString(R.string.hello_user, user.getFirstName()));
//        } else {
//            profilePictureView.setProfileId(null);
//            greeting.setText(null);
//        }
    }

    @SuppressWarnings("incomplete-switch")
    private void handlePendingAction() {
        PendingAction previouslyPendingAction = pendingAction;
        // These actions may re-set pendingAction if they are still pending, but we assume they
        // will succeed.
        pendingAction = PendingAction.NONE;

        switch (previouslyPendingAction) {
            case POST_PHOTO:
                break;
            case POST_STATUS_UPDATE:
                postStatusUpdate();
                break;
        }
    }

    private interface GraphObjectWithId extends GraphObject {
        String getId();
    }

    private void showPublishResult(String message, GraphObject result, FacebookRequestError error) {
        String title = null;
        String alertMessage = null;
        if (error == null) {
            title = getString(R.string.success);
            String id = result.cast(GraphObjectWithId.class).getId();
            alertMessage = getString(R.string.successfully_posted_post, message, id);
        } else {
            title = getString(R.string.error);
            alertMessage = error.getErrorMessage();
        }

        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(alertMessage)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private void onClickPostStatusUpdate() {
        performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
    }

    private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
        return new FacebookDialog.ShareDialogBuilder(this)
                .setName("Hello Facebook")
                .setDescription("The 'Hello Facebook' sample application showcases simple Facebook integration")
                .setLink("http://developers.facebook.com/android");
    }

    private void postStatusUpdate() {
        if (canPresentShareDialog) {
            FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
            uiHelper.trackPendingDialogCall(shareDialog.present());
        } else if (user != null && hasPublishPermission()) {
            final String message = getString(R.string.status_update, user.getFirstName(), (new Date().toString()));
            Request request = Request
                    .newStatusUpdateRequest(Session.getActiveSession(), message, place, tags, new Request.Callback() {
                        @Override
                        public void onCompleted(Response response) {
                            showPublishResult(message, response.getGraphObject(), response.getError());
                        }
                    });
            request.executeAsync();
        } else {
            pendingAction = PendingAction.POST_STATUS_UPDATE;
        }
    }

    private void onClickPostPhoto() {
        performPublish(PendingAction.POST_PHOTO, canPresentShareDialogWithPhotos);
    }

    private FacebookDialog.PhotoShareDialogBuilder createShareDialogBuilderForPhoto(Bitmap... photos) {
        return new FacebookDialog.PhotoShareDialogBuilder(this)
                .addPhotos(Arrays.asList(photos));
    }

    private void onFriendPickerDone(FriendPickerFragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        fm.popBackStack();

        String results = "";

        List<GraphUser> selection = fragment.getSelection();
        tags = selection;
        if (selection != null && selection.size() > 0) {
            ArrayList<String> names = new ArrayList<String>();
            for (GraphUser user : selection) {
                names.add(user.getName());
            }
            results = TextUtils.join(", ", names);
        } else {
            results = getString(R.string.no_friends_selected);
        }

        showAlert(getString(R.string.you_picked), results);
    }

    private void onPlacePickerDone(PlacePickerFragment fragment) {
        FragmentManager fm = getSupportFragmentManager();
        fm.popBackStack();

        String result = "";

        GraphPlace selection = fragment.getSelection();
        if (selection != null) {
            result = selection.getName();
        } else {
            result = getString(R.string.no_place_selected);
        }

        place = selection;

        showAlert(getString(R.string.you_picked), result);
    }

    private void setPlacePickerListeners(final PlacePickerFragment fragment) {
        fragment.setOnDoneButtonClickedListener(new PlacePickerFragment.OnDoneButtonClickedListener() {
            @Override
            public void onDoneButtonClicked(PickerFragment<?> pickerFragment) {
                onPlacePickerDone(fragment);
            }
        });
        fragment.setOnSelectionChangedListener(new PlacePickerFragment.OnSelectionChangedListener() {
            @Override
            public void onSelectionChanged(PickerFragment<?> pickerFragment) {
                if (fragment.getSelection() != null) {
                    onPlacePickerDone(fragment);
                }
            }
        });
    }

    private void showAlert(String title, String message) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(message)
                .setPositiveButton(R.string.ok, null)
                .show();
    }

    private boolean hasPublishPermission() {
        Session session = Session.getActiveSession();
        return session != null && session.getPermissions().contains("publish_actions");
    }

    private void performPublish(PendingAction action, boolean allowNoSession) {
        Session session = Session.getActiveSession();
        if (session != null) {
            pendingAction = action;
            if (hasPublishPermission()) {
                // We can do the action right away.
                handlePendingAction();
                return;
            } else if (session.isOpened()) {
                // We need to get new permissions, then complete the action when we get called back.
                session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
                return;
            }
        }

        if (allowNoSession) {
            pendingAction = action;
            handlePendingAction();
        }
    }
}
